import Vue from 'vue';
import Vuex from 'vuex';
import {
	login
} from '../utils/api/modules/user';

// 必须先调用 Vue.use(Vuex)
Vue.use(Vuex);

export default new Vuex.Store({
	state: {
		token: uni.getStorageSync('token') || '', // 初始化时从本地存储读取
		user: ''
	},
	mutations: {
		SET_TOKEN(state, token) {
			state.token = token;
			uni.setStorageSync('token', token); // 同时存入本地存储
		},
		CLEAR_TOKEN(state) {
			state.token = '';
			uni.removeStorageSync('token'); // 清除本地存储
			// 清除 token 后自动跳转登录页
			uni.removeStorageSync('user');
			uni.redirectTo({
				url: '/pages/login'
			});
		},
		SET_USER(state, user) {
			state.user = user;
			uni.setStorageSync('user', user);
		},
		// 新增：更新用户对象的单个字段
		UPDATE_USER_FIELD(state, {
			field,
			value
		}) {
			if (state.user && field in state.user) {
				// 使用Vue.set确保响应式更新
				Vue.set(state.user, field, value);
				// 更新本地存储
				uni.setStorageSync('user', state.user);
			}
		}
	},
	actions: {
		// 退出登录
		logout({
			commit
		}) {
			commit('CLEAR_TOKEN');
		},
		    updateUserField({ commit }, payload) {
		      commit('UPDATE_USER_FIELD', payload);
		    }
	},
	getters: {
		// 判断是否登录
		isLoggedIn: state => !!state.token,

		// 获取token
		getToken: state => state.token,

		getUser: state => state.user,
	}
});